<template>
  <div class="employees-container">
    <div class="app-container">
      <template>
        <div class="employees-container">
          <div class="app-container">
            <page-tools>
              <template #left>
                <span>总记录数: {{ total }} 条</span>
              </template>

              <template #right>
                <el-button v-permission="'excel_import'" type="warning" size="small" @click="$router.push('/import/index?type=import')">excel导入</el-button>
                <el-button
                  v-permission="'excel_export'"
                  type="danger"
                  size="small"
                  @click="hanldeDownload"
                >excel导出</el-button>
                <el-button v-permission="'emp_add'" type="primary" size="small" @click="addsEmployee">新增员工</el-button>
              </template>
            </page-tools>

            <el-card v-loading="isLoading" style="margin-top: 10px;">
              <el-table border :data="list">
                <el-table-column label="序号" type="index" width="80" :index="indexMethod" />
                <el-table-column prop="username" label="姓名" />
                <el-table-column prop="staffPhoto" label="头像">
                  <template #default="{row}">
                    <img v-imgerror="errImg" :src="row.staffPhoto || replaceImg" class="img_box">
                  </template>
                </el-table-column>
                <el-table-column prop="mobile" label="手机号" />
                <el-table-column prop="workNumber" label="工号" />
                <el-table-column prop="formOfEmployment" label="聘用形式" :formatter="formattText" />
                <el-table-column prop="departmentName" label="部门" />
                <el-table-column prop="timeOfEntry" label="入职时间">
                  <template #default="{row}">
                    {{ formmatTime(row.timeOfEntry) }}
                  </template>
                </el-table-column>

                <el-table-column label="操作" width="280">
                  <template #default="{row}">
                    <el-button v-permission="'emp_edit'" type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
                    <el-button v-permission="'assign_role'" type="text" size="small" @click="isShowRoleDialog(row.id)">分配角色</el-button>
                    <el-button v-permission="'emp_delete'" type="text" size="small" @click="delEmployees(row.id)">删除</el-button>
                  </template>
                </el-table-column>

              </el-table>
              <!-- 分页组件 -->
              <div style="height: 60px; margin-top: 10px">
                <el-pagination
                  :current-page="page"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="size"
                  layout="total, sizes, prev, pager, next"
                  :total="total"
                  background
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
                <!-- <el-pagination layout="prev, pager, next" /> -->
              </div>
            </el-card>
            <!-- 添加弹出层 -->
            <addEmployee ref="addEmp" :show-dialog.sync="showDialog" :titile="titile" @add="getEmpList" />
            <!-- 权限弹出层 -->
            <assignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import { getEmpListApi, delEmployeesListApi } from '@/api/employees'
import { Message } from 'element-ui'
import addEmployee from './components/add-employee.vue'
import assignRole from './components/assign-role.vue'
// 导入枚举
import Enum from '@/constant/employees'
// 导入时间格式化插件
import dayjs from 'dayjs'
// 导入替换头像
import replaceImg from '@/assets/common/bigUserHeader.png'
// 头像加载失败
import errImg from '@/assets/404_images/1.jpg'
import { mapGetters } from 'vuex'
export default {
  name: 'Employees',
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      page: 1,
      size: 10,
      list: [],
      total: 0,
      // 添加弹出层显示隐藏
      showDialog: false,
      titile: '',
      isLoading: false,
      // 无图替换头像
      replaceImg,
      // 有图替换头像
      errImg,
      // 权限模块显示隐藏
      showRoleDialog: false,
      // 用户ID
      userId: ''
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  created() {
    this.getEmpList()
  },
  methods: {
    judgment(val) {
      return this.roles.points.includes(val)
    },
    /**
     * 权限框显示隐藏
     */
    isShowRoleDialog(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    /**
     * 导出excel数据
     */
    hanldeDownload() {
      import('@/vendor/Export2Excel').then(async excel => {
        const { data: { rows }} = await getEmpListApi(1, this.total)
        // console.log(rows)
        const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        const headersRelations = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const list = this.getTwoDoubleList(rows, headersArr, headersRelations)
        excel.export_json_to_excel({
          // 表头
          header: headersArr,
          data: list,
          // 文件名
          filename: '员工信息',
          // 宽度是否自适应
          autoWidth: true,
          // 文件后缀名
          bookType: 'xlsx'
        })
      })
    },
    /**
     * 转换二维数组方法
     */
    getTwoDoubleList(rows, headersArr, headersRelations) {
      const list = []
      // 1.遍历获取得到的数据
      rows.forEach(e => {
        const oneArr = []
        headersArr.forEach(x => {
          // 获取键
          // headersRelations[x]
          // 将值加到一级数组
          // 处理聘用形式
          let value = e[headersRelations[x]]
          if (headersRelations[x] === 'formOfEmployment') {
            const hireType = Enum.hireType
            const res = hireType.find(e => e.id === +value)
            value = res ? res.value : '未声明'
          }
          if (['timeOfEntry', 'correctionTime'].includes(headersRelations[x])) {
            value = value ? dayjs(value).format('YYYY - MM - DD') : '未声明'
          }
          oneArr.push(value)
        })
        // 存入新数组
        list.push(oneArr)
      })
      // rows.map(e => {
      //   const oneArr = []
      //   headersArr.forEach(x => {
      //     // 获取键
      //     // headersRelations[x]
      //     // 将值加到一级数组
      //     e = oneArr.push(e[headersRelations[x]])
      //   })
      //   return e
      // })
      return list
    },
    /**
     * 时间格式化
     */
    formmatTime(time) {
      return time ? dayjs(time).format('YYYY - MM - DD') : '未声明'
    },
    /**
     * 通过返回的数据类型 来判断入职方式
     */
    formattText(row, column, cellValue, index) {
      const hireType = Enum.hireType
      const res = hireType.find(e => e.id === +cellValue)
      return res ? res.value : '未声明'
    },
    /**
     * 添加显示弹出框
     */
    addsEmployee() {
      this.showDialog = true
      this.titile = '添加员工'
    },
    /**
     * 删除功能
     */
    delEmployees(id) {
      this.$confirm('此操作将永久删除该员工信息是否继续？', '温馨提示').then(async() => {
        // 1.确认后调用接口
        await delEmployeesListApi(id)
        // 2.提示删除成功
        Message.success('删除成功')
        // 3.如果删除的是某页的最后一项 回到上一页
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        // 4.渲染页面
        this.getEmpList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 列表前索引
    // 此方法num 形参默认从0开始
    indexMethod(num) {
      // 前方索引应当为 (页码-1)*页容量 +num +1
      return (this.page - 1) * this.size + num + 1
    },
    /**
     * 切换页时候执行
     */
    handleCurrentChange(val) {
      // 1.切换也页 将当前页赋值给page
      this.page = val
      // 2.从新调用接口
      this.getEmpList()
    },
    /**
     * 切换页容量执行
     */
    handleSizeChange(val) {
      // 1.切换也页 将当前页赋值给page
      this.size = val
      // 2.更改页容量默认显示第一页
      this.page = 1
      // 3.从新调用接口
      this.getEmpList()
    },
    /**
     * 请求接口 修改员工入职方式
     */
    async getEmpList() {
      this.isLoading = true
      const { data } = await getEmpListApi(this.page, this.size)
      this.list = data.rows
      this.total = data.total
      this.isLoading = false
    }
  }
}
</script>

<style lang='scss' scoped>
.img_box{
  width: 100px;
  height: 100px;
}
</style>

